package offerv1;

public class Offer36 {
    Node current;

    //left左指针  right右指针
    public Node treeToDoublyList(Node root) {
        Node virtual = new Node(-1);
        current = virtual;
        dfs(root);
        return virtual.right;
    }

    private void dfs(Node node) {
        if (node == null) {
            return;
        }

        Node left = node.left;
        Node right = node.right;

        dfs(left);
        node.left = current;
        current.right = node;
        current = node;
        dfs(right);

    }

    class Node {
        public int val;
        public Node left;
        public Node right;

        public Node() {
        }

        public Node(int _val) {
            val = _val;
        }

        public Node(int _val, Node _left, Node _right) {
            val = _val;
            left = _left;
            right = _right;
        }
    }

    Node pre, head;
    public Node treeToDoublyList1(Node root) {
        if(root == null) return null;
        dfs1(root);
        head.left = pre;
        pre.right = head;
        return head;
    }

    //当前节点到加入到链表
    void dfs1(Node cur) {
        if(cur == null) return;
        dfs(cur.left);
        if(pre != null) pre.right = cur;
        else head = cur;
        cur.left = pre;
        pre = cur;
        dfs(cur.right);
    }
}
